//
//  HomeViewController.m
//  Baby
//
//  Created by YC on 2017/8/8.
//  Copyright © 2017年 YC. All rights reserved.
//

#import "HomeViewController.h"
#import "HomeHeaderView.h"
#import "HomeListCell.h"

#import "HomeSection+CoreDataClass.h"
#import "HomeList+CoreDataClass.h"

#import "StatisticsViewController.h"
#import "AddendumTableViewController.h"
#import "DetailTableViewController.h"

#import "Baby-Swift.h"

@interface HomeViewController ()<UITableViewDelegate, UITableViewDataSource> {
    
}

@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UIButton *quickAddButton;

@property (strong, nonatomic) NSArray *dataArray;

@end

@implementation HomeViewController

+ (instancetype)getInstance {
    
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main"
                                                         bundle:nil];
    id vc = [storyboard instantiateViewControllerWithIdentifier:@"HomeViewController"];
    
    return vc;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setupUI];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
}

- (void)setupUI {
    self.tableView.tableFooterView = [[UIView alloc] init];
    
    self.quickAddButton.layer.cornerRadius = 32;
    self.quickAddButton.layer.masksToBounds = true;
}

#pragma mark - UITableView Delegate

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.dataArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    HomeSection *s = self.dataArray[section];
    return s.list.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 30.0;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    HomeSection *sectionModel = self.dataArray[section];
    int timesCount = 0;
    
    for (HomeList *list in sectionModel.list) {
        timesCount += list.times;
    }
    
    HomeHeaderView *view = [HomeHeaderView headerViewWithTableView:tableView];
    view.dateLabel.text = [sectionModel dateStr];
    view.timesCountLabel.text = [NSString stringWithFormat:@"共 %d 次",timesCount];
    
    return view;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    HomeSection *sectionModel = self.dataArray[indexPath.section];
    HomeList *listModel = sectionModel.list[indexPath.row];
    
    HomeListCell *cell = [HomeListCell cellWithTableView:tableView];
    
    cell.timeLabel.text = [listModel timeStr];
    cell.timesLabel.text = [listModel timesStr];
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    HomeSection *sectionModel = self.dataArray[indexPath.section];
    HomeList *listModel = sectionModel.list[indexPath.row];
    
    DetailTableViewController *vc = [DetailTableViewController getInstance];
    vc.list = listModel;
    
    [self.navigationController pushViewController:vc animated:true];
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    return true;
}

- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath {
    return @"删除";
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        HomeSection *sectionModel = self.dataArray[indexPath.section];
        
        if (sectionModel.list.count == 1) {
            [sectionModel MR_deleteEntity];

            [self save];
            self.dataArray = [HomeSection MR_findAllSortedBy:@"date" ascending:false];
            [self.tableView reloadData];
        }else {
            [sectionModel.list[indexPath.row] MR_deleteEntity];
            
            [self save];
            [tableView deleteRowsAtIndexPaths:[NSMutableArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
        }
    }
}

#pragma mark - Action
- (IBAction)clickStatisticsButton:(id)sender {
    StatisticsViewController *vc = [StatisticsViewController getInstance];
    
    [self.navigationController pushViewController:vc animated:true];
}

- (IBAction)clickAddendumButton:(id)sender {
    AddendumTableViewController *vc = [AddendumTableViewController getInstance];
    vc.sections = self.dataArray;
    __weak __typeof(&*self)weakSelf = self;
    vc.doneBlock = ^{
        [weakSelf save];
        weakSelf.dataArray = [HomeSection MR_findAllSortedBy:@"date" ascending:false];
        [weakSelf.tableView reloadData];
    };
    
    [self.navigationController pushViewController:vc animated:true];
}

- (IBAction)clickQuickAddButton:(UIButton *)sender {
    NSDate *now = [NSDate date];
    
    HomeList *list = [HomeList MR_createEntity];
    list.time = now;
    list.times = 1;
    list.remark = @"快速记录";
    
    BOOL isHaveSameDay = false;
    
    for (HomeSection *section in self.dataArray) {
        isHaveSameDay = [Tools whetherTheSameDay:section.date date2:now];
        
        if (isHaveSameDay) {
            NSMutableOrderedSet *set = [section mutableOrderedSetValueForKey:@"list"];
            
            for (int i = 0; i < set.count; i++) {
                HomeList *l = [set objectAtIndex:i];
                
                NSTimeInterval t = [l.time timeIntervalSinceDate:list.time];
                
                if (t < 0) {
                    [set insertObject:list atIndex:i];
                    break;
                }else if (i == set.count - 1) {
                    [set addObject:list];
                }
            }
            
            break;
        }
    }
    
    if (isHaveSameDay == false) {
        HomeSection *section = [HomeSection MR_createEntity];
        
        section.date = now;
        
        NSMutableOrderedSet *set = [section mutableOrderedSetValueForKey:@"list"];
        [set insertObject:list atIndex:0];
    }
    
    
    [self save];

    self.dataArray = [HomeSection MR_findAllSortedBy:@"date" ascending:false];
    
    [self.tableView reloadData];
}

- (void)save {
    [[NSManagedObjectContext MR_defaultContext] MR_saveToPersistentStoreAndWait];
}

#pragma mark - Getter Setter
- (NSArray *)dataArray {
    if (_dataArray == nil || _dataArray.count == 0) {
        _dataArray = [HomeSection MR_findAllSortedBy:@"date" ascending:false];
    }
    
    return _dataArray;
}


@end
